/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.Image;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.TaskMark;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.ImageService;
import me.zhengjie.modules.system.service.TaskMarkService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.ImageMapper;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author whj
* @date 2021-01-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "api/taskMark管理")
@RequestMapping("/api/taskMark")
public class TaskMarkController {

    private final TaskMarkService taskMarkService;
    private final UserService userService;
    private final ImageService imageService;
    private final ImageMapper imageMapper;
    private final UserMapper userMapper;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('taskMark:list')")
    public void download(HttpServletResponse response, TaskMarkQueryCriteria criteria) throws IOException {
        taskMarkService.download(taskMarkService.queryAll(criteria), response);
    }

    @Log("分配任务")
    @ApiOperation("分配任务")
    @PostMapping(value = "/assign")
    public void assign(@RequestBody TaskAssignVo taskAssignVo) throws Exception {
        //创建任务
        TaskMark taskMark = new TaskMark();
        taskMark.setTaskName(taskAssignVo.getTaskName());
        taskMark.setStatus(Long.valueOf(1));
        taskMark.setNumImage(Long.valueOf(0));
        taskMark.setNumFinish(Long.valueOf(0));
        taskMark.setNumChecked(Long.valueOf(0));
        int numFinishedCount =0;
        int numCheckedCount =0;
        for(ImageVo imageVo : taskAssignVo.getImageList()){
            ImageQueryCriteria imageQueryCriteria = new ImageQueryCriteria();
            imageQueryCriteria.setIamgePath(imageVo.getFilepath());
            List<Image> i = imageMapper.toEntity(imageService.queryAll(imageQueryCriteria));
            if (i.size() == 0)
                continue;
            if (i.get(0).getStatus()==4) numCheckedCount++;
            if (i.get(0).getStatus()==3 || i.get(0).getStatus()==4 || i.get(0).getStatus()==0) numFinishedCount++;
        }
        taskMark.setNumChecked(Long.valueOf(numCheckedCount));
        taskMark.setNumFinish(Long.valueOf(numFinishedCount));

        //对图片和文件夹进行分类
        String folder = "";
        String image = "";
        for(String s : taskAssignVo.getFileList()){
            String[] bits = s.split("/");
            String lastone = bits[bits.length-1];
            if(lastone.endsWith(".jpg") || lastone.endsWith(".jpeg") || lastone.endsWith(".png") || lastone.endsWith(".tif")){
                image += s;
                image += ",";
            }else{
                folder += s;
                folder += ",";
            }
        }
        if(folder.length() > 1)     folder = folder.substring(0, folder.length() - 1);
        if(image.length() > 1)      image = image.substring(0, image.length() - 1);
        String path = "[(folder:" + folder + "),(image:" + image + ")]";
        taskMark.setFileList(path);
        taskMark.setNumImage(Long.valueOf(taskAssignVo.getImageList().size()));

        //创建image和image-taskMark表
        List<Image> newImageList = new ArrayList<>();
        for(ImageVo imageVo : taskAssignVo.getImageList()){
            ImageQueryCriteria imageQueryCriteria = new ImageQueryCriteria();
            imageQueryCriteria.setIamgePath(imageVo.getFilepath());
            List<Image> i = imageMapper.toEntity(imageService.queryAll(imageQueryCriteria));    //检测是否图片是否已经存在数据库
            Image new_image;
            if(i.size() > 0){   //图片存在数据库
                new_image = i.get(0);
                newImageList.add(new_image);
            } else{   //图片不存在数据库
                new_image = new Image();
                new_image.setHeight(imageVo.getHeight());
                new_image.setSize(imageVo.getSize());
                new_image.setWidth(imageVo.getWidth());
                new_image.setIamgePath(imageVo.getFilepath());
                new_image.setImageName(imageVo.getFilename());
                new_image.setStatus(Long.valueOf(1));
                new_image.setNumBox(Long.valueOf(0));
                imageService.create(new_image);
                Image reImage = imageMapper.toEntity(imageService.queryAll(imageQueryCriteria)).get(0);
                newImageList.add(reImage);
            }
        }
        taskMark.setImages(newImageList);

        //创建用户-任务表
        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        userQueryCriteria.setId(taskAssignVo.getUserId());
        List<User> userList = userMapper.toEntity(userService.queryAll(userQueryCriteria));
        taskMark.setUsers(userList);
        taskMarkService.create(taskMark);
    }


    @PostMapping(value = "/merits")
    @Log("查询绩效")
    @ApiOperation("查询绩效")
    public ResponseEntity<Object> queryMerits(@Validated @RequestBody TaskMarkQueryCriteria criteria){
        return new ResponseEntity<>(taskMarkService.queryMerits(criteria),HttpStatus.OK);
    }



    @GetMapping
    @Log("查询api/taskMark")
    @ApiOperation("查询api/taskMark")
    public ResponseEntity<Object> query(TaskMarkQueryCriteria criteria, Pageable pageable){
        Long userId = SecurityUtils.getCurrentUserId();
        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        userQueryCriteria.setId(userId);
        List<UserDto> userDtos = userService.queryAll(userQueryCriteria);

        for(RoleSmallDto r : userDtos.get(0).getRoles()){
            if(r.getLevel()==1 ||r.getLevel()==2){     //若为管理员
                return new ResponseEntity<>(taskMarkService.queryAll(criteria,pageable),HttpStatus.OK);
            }
        }
        criteria.setUserId(userId);
        return new ResponseEntity<>(taskMarkService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @GetMapping(value = "/member")
    @Log("查询任务所属员工")
    @ApiOperation("查询任务所属员工") public ResponseEntity<Object> query(@RequestParam Integer markTaskId){
        return new ResponseEntity<>(taskMarkService.queryTaskMember(markTaskId),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增api/taskMark")
    @ApiOperation("新增api/taskMark")
    @PreAuthorize("@el.check('taskMark:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody TaskMark resources){
        return new ResponseEntity<>(taskMarkService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改api/taskMark")
    @ApiOperation("修改api/taskMark")
    @PreAuthorize("@el.check('taskMark:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody TaskMark resources){
        taskMarkService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除api/taskMark")
    @ApiOperation("删除api/taskMark")
    @PreAuthorize("@el.check('taskMark:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        taskMarkService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
